package com.wish.g01.finance.controller;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jeequan.jeepay.Jeepay;
import com.jeequan.jeepay.JeepayClient;
import com.jeequan.jeepay.exception.JeepayException;
import com.jeequan.jeepay.model.PayOrderCreateReqModel;
import com.jeequan.jeepay.request.PayOrderCreateRequest;
import com.jeequan.jeepay.response.PayOrderCreateResponse;
import com.wish.g01.base.dto.*;
import com.wish.g01.base.entity.CfContract;
import com.wish.g01.base.entity.CwPaymentPlan;
import com.wish.g01.base.entity.CwReceiptPlan;
import com.wish.g01.base.service.ICfContractService;
import com.wish.g01.base.service.ICwPaymentPlanService;
import com.wish.g01.base.service.ICwReceiptPlanService;
import com.wish.g01.common.core.web.controller.BaseController;
import com.wish.g01.common.core.web.domain.AjaxResult;
import com.wish.g01.common.core.web.page.TableDataInfo;
import com.wish.g01.common.security.annotation.PreAuthorize;
import com.wish.g01.common.security.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.WebUtils;

/**
 * 收款计划Controller
 * 
 * @author wish
 * @date 2022-05-26
 */
@RestController
@RequestMapping("/plan")
public class TCwReceiptPlanController extends BaseController
{
    @Autowired
    private ICwReceiptPlanService tCwReceiptPlanService;

    /**
     * 查询收款计划列表
     */
    @PreAuthorize(hasPermi = "finance:plan:list")
    @GetMapping("/list")
    //收款计划模糊查询及列表展示
    public TableDataInfo list(CwReceiptPlanDto dto)
    {
        startPage();
        //List<CwReceiptPlan> list = tCwReceiptPlanService.listShow(cwReceiptPlanDto);
        QueryWrapper<CwReceiptPlan> wrapper = new QueryWrapper<>();
        if (StringUtils.isNoneBlank(dto.getContractNo())) {
            wrapper.like("contract_no",dto.getContractNo());
        }
        if (dto.getCollectionDateStart() != null) {
            wrapper.ge("collection_date",dto.getCollectionDateStart());
        }
        if (dto.getCollectionDateEnd() != null) {
            wrapper.le("collection_date",dto.getCollectionDateEnd());
        }
        if (dto.getSkStatus() != null) {
            wrapper.eq("sk_status",dto.getSkStatus());
        }
        if (dto.getRealCollectionDateStart() != null) {
            wrapper.ge("real_collection_date",dto.getRealCollectionDateStart());
        }
        if (dto.getRealCollectionDateEnd() != null) {
            wrapper.le("real_collection_date",dto.getRealCollectionDateEnd());
        }
        if (dto.getBillType() != null) {
            wrapper.eq("bill_type",dto.getBillType());
        }
        startPage();
        List<CwReceiptPlan> list = tCwReceiptPlanService.list(wrapper);
        return getDataTable(list);
    }

    /**
     * 收款计划数据查询
     */
    @PreAuthorize(hasPermi = "finance:plan:sumList")
    @GetMapping("/sumList")
    //收款计划模糊查询及列表展示
    public TableDataInfo sumList(CwReceiptPlanDto cwReceiptPlanDto)
    {
        startPage();
        List<CwReceiptPlan> list = tCwReceiptPlanService.sumList(cwReceiptPlanDto);
        return getDataTable(list);
    }

    @Autowired
    ICwPaymentPlanService itCwPaymentPlanService;

    //添加方法
    @PostMapping("save")
    public void save(@RequestBody TCwPaymentPlanDto dto) {
        System.out.println("--------");
        ArrayList<CostType> costTypes = dto.getCostTypes();
        Long id = null;
        for (CostType costType : costTypes) {
            dto.setId(id);
            //生成随机单号
            String s = RandomUtil.randomStringUpper(10);
            dto.setPayOrderNo(s);
            dto.setItemType(costType.getItemType());
            dto.setPaymentAmount(costType.getPaymentAmount());
            dto.setRealPaymentAmount(costType.getRealPaymentAmount());
            dto.setCreateUserid(SecurityUtils.getUserId());
            dto.setCreateTime(new Date());
            itCwPaymentPlanService.save(dto);
        }
    }


    /*查询付款计划*/
    @PostMapping("paymentList")
    public PageInfo<TCwPaymentPlanDto> paymentList(@RequestBody TCwPaymentPlanDto tCwPaymentPlanDto) {
        PageHelper.startPage(tCwPaymentPlanDto.getPageNum(), tCwPaymentPlanDto.getPageSize());
        List<TCwPaymentPlanDto> list = itCwPaymentPlanService.paymentList(tCwPaymentPlanDto);
        PageInfo<TCwPaymentPlanDto> tCwPaymentPlanDtoPageInfo = new PageInfo<>(list);
        System.out.println(list);
        return tCwPaymentPlanDtoPageInfo;
    }


    /*获取所有账单类型*/
    @GetMapping("itemTypeList")
    public ItemType[] itemTypeList() {
        ItemType[] values = ItemType.values();
        return values;
    }

    /*获取所有付款状态*/
    @GetMapping("payStateList")
    public PayState[] payStateList() {
        PayState[] values = PayState.values();
        return values;
    }

    /*获取所有付款类型*/
    @GetMapping("billTypeList")
    public BillType[] payTypeList() {
        BillType[] values = BillType.values();
        return values;
    }

    /*获取所有支付方式*/
    @GetMapping("payMethodList")
    public PayMethod[] payMethodList() {
        PayMethod[] values = PayMethod.values();
        return values;
    }

    @PostMapping("settles")
    public String settles(@RequestBody CwPaymentPlan cwPaymentPlan) throws JeepayException {
        Map<String, Object> params = convertRequestParamsToMap(cwPaymentPlan);
        String token="eyJhbGciOiJIUzUxMiJ9.eyJjYWNoZUtleSI6IlRPS0VOXzEwMDAwMV84MjliMDZiYS1lZTAxLTQwNzctYTdkYy0yMzA5ZWU4MWZjOGMiLCJjcmVhdGVkIjoxNjU0NTI3NjkzNTE5LCJzeXNVc2VySWQiOjEwMDAwMX0.eT97vtTv_gWuVTJvhtnY-bhp_A2g3FSG0XxIIt_blrG39UCgZi8VeJ0ugIyde9B7Z3MEY5HqAJdfIzxhVKz4mw";
        String url="http://localhost:9218/api/paytest/payOrders";
        String url2="http://43.142.35.71:9218/api/paytest/payOrders";
        //链式构建请求
        String result2 = HttpRequest.post(url2)
                //.header("iToken", token)//头信息，多个头信息多次调用此方法即可
                .form(params)//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
        // 响应数据
        System.out.println(result2);
        return result2;
    }

    /**
     * 将request中的参数转换成Map
     */
    private static Map<String, Object> convertRequestParamsToMap(CwPaymentPlan cwPaymentPlan) {
        Map signMap = new HashMap<>();
        signMap.put("platId", cwPaymentPlan.getId()+"");
        signMap.put("appId", "629c0238dbc51244c3073587");
        int random = (int)(Math.random()*100);
        signMap.put("mchOrderNo", "M16545257339801445"+random);
        signMap.put("amount", cwPaymentPlan.getPaymentAmount());
        signMap.put("reqTime", "20190723141000");
        signMap.put("subject", "订单支付");
        signMap.put("version", "1.0");
        signMap.put("body", "对账批次");
        signMap.put("wayCode","ALI_PC");
        signMap.put("currency","cny");
        signMap.put("divisionMode",0);
        signMap.put("orderTitle","接口调试");
        signMap.put("authCode","");
        return signMap;
    }

    @Autowired
    ICfContractService itCfContractService;

    @GetMapping("/getMsg")
    public AjaxResult getMsg(CfContract contract) {
        CfContract byId = itCfContractService.getById(contract.getId());
        return AjaxResult.success(byId);
    }
}
